package com.github.cyf.util.image;

import cn.hutool.core.util.ArrayUtil;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author chenyifan
 * @create 2024-11-22 10:28
 */
public class ImageJoinUtil {

    /**
     * 纵向拼接一组图像
     * @param pics 将要拼接的图像数组
     * @param dstPic 写入图像路径
     * @return
     */
    public static File joinImageByY(File[] pics, String dstPic) {
        if (ArrayUtil.isEmpty(pics)) {
            return null;
        }
        int picCount = pics.length;
        BufferedImage[] images = new BufferedImage[picCount];
        try {
            for (int i = 0; i < picCount; i++) {
                images[i] = ImageIO.read(pics[i]);
            }

            // 计算拼接图片宽高
            int dst_height = 0;
            int dst_width = 0;
            for (int i = 0; i < images.length; i++) {
                dst_width = Math.max(dst_width, images[i].getWidth());
                dst_height += images[i].getHeight();
            }

            // 使用 TYPE_INT_ARGB 支持透明度
            BufferedImage ImageNew = new BufferedImage(dst_width, dst_height, BufferedImage.TYPE_INT_ARGB);
            int height_i = 0;
            for (int i = 0; i < images.length; i++) {
                // 绘制图片到新的 BufferedImage 上，保留透明度
                Graphics2D g2d = ImageNew.createGraphics();
                g2d.drawImage(images[i], 0, height_i, null);
                g2d.dispose();
                height_i += images[i].getHeight();
            }

            File outFile = new File(dstPic);
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            ImageIO.write(ImageNew, "png", outFile);
            return outFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}